package Ep04_String._0151;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/19 17:52
 * 说明：力扣 0151翻转字符串中的单词 —— 双指针
 */

public class DoublePointer {
    public String reverseWords(String s) {
        if (s.length() == 1){
            return s;
        }
        StringBuilder sb = removeSpaceMine(s);
        int len = sb.length()-1;
        reverseStringMine(sb, 0, len);
        reverseEachWordMine(sb);
        return sb.toString();
    }



    // 我的去除空格方法
    private StringBuilder removeSpaceMine(String s){
        StringBuilder sb = new StringBuilder();
        int start = 0, end = s.length()-1;
        while (s.charAt(start) != ' ')  start++;
        while (s.charAt(end) != ' ') end--;
        while (start < end){
            char c = s.charAt(start);
            if (c != ' ' || sb.charAt(sb.length()-1) != ' ') {
                sb.append(c);
            }
            start++;
        }
        return sb;
    }

    private void reverseStringMine(StringBuilder sb, int start, int end){
        while (start < end){
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }

    private void reverseEachWordMine(StringBuilder sb){
        int start = 0, end = 1, n = sb.length();
        while (start < n){
            while (end < n && sb.charAt(end) != ' '){
                end++;
            }
            reverseStringMine(sb, start, end - 1);
            start = end + 1;
            end = start + 1;
        }
    }



//    private StringBuilder removeSpace(String s){
//        int start = 0, end = s.length()-1;
//        while (s.charAt(start) == ' ') start++;
//        while (s.charAt(end) == ' ') end--;
//        StringBuilder sb = new StringBuilder();
//        while (start <= end ){  // 从头遍历到尾
//            char c = s.charAt(start);
//            // 左条件保证非空格字符会被添加进StringBuilder，右条件保证单独的空格会被添加，因此使用 ||
//            if (c != ' ' || sb.charAt(sb.length() - 1) != ' '){
//                sb.append(c);
//            }
//            start++;
//        }
//        return sb;
//    }
}
